package coml.allen.api.qos;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.QueueingConsumer;

/**
 * @author sesshomaru
 * @date 2020/11/14 16:23
 */
public class Consumer {

    public static void main(String[] args) throws Exception{
        ConnectionFactory connectionFactory = new ConnectionFactory();

        connectionFactory.setHost("192.168.1.102");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");

        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();

        // 开启消息发送确认
        channel.confirmSelect();

        String exchange = "test_qos_ex";
        String routingKey = "confirm.#";
        String queueName = "test-qos-queue";

        channel.exchangeDeclare(exchange,"topic",true);
        channel.queueDeclare(queueName,true,false,false,null);
        channel.queueBind(queueName,exchange,routingKey);

        // 使用消费限流
        /**
         * int prefetchSize,    消息大小限制
         * int prefetchCount, 一次可以处理多少条消息  假设有100条没被消费的消息，如果设置为3 表示消费时不要直接把100条一起发过来而是每次发3条过来即可
         *              3条被消费后我发给你ack然后你再推3条 直到100条消费完
         * boolean global   这个限流策略实在什么级别上应用的，ture 如果queue级别 或者  false 消费者下游服务级别
         */
        channel.basicQos(0,1,true);

        /**
         * 如果使用限流，一定腰包autoAck设置为false 关闭 必须手动签收
         */
        channel.basicConsume(queueName, false ,new MyConsumer(channel));


    }
}
